package com.bjbn.service.impl;

import com.bjbn.config.ScheduleConfig;
import com.bjbn.dto.DataCleanResult;
import com.bjbn.mapper.BridgeInfoHistoryMapper;
import com.bjbn.service.BridgeInfoHistoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 廊桥_登机桥信息_模型 Service实现类
 */
@Slf4j
@Service
public class BridgeInfoHistoryServiceImpl implements BridgeInfoHistoryService {

    @Autowired
    private BridgeInfoHistoryMapper bridgeInfoHistoryMapper;

    @Autowired
    private ScheduleConfig scheduleConfig;

    /**
     * 清理三个月之前的数据，使用分批处理小事务方式
     */
    @Override
    public void cleanExpiredData() {
        cleanExpiredDataWithResult();
    }

    /**
     * 清理三个月之前的数据，返回详细结果
     */
    @Override
    public DataCleanResult cleanExpiredDataWithResult() {
        log.info("开始清理三个月之前的廊桥_登机桥信息历史数据");
        Date startTime = new Date();

        // 获取配置的保留天数，默认为90天
        int retentionDays = scheduleConfig.getRetention() != null && scheduleConfig.getRetention().getBridgeInfoDays() != null 
            ? scheduleConfig.getRetention().getBridgeInfoDays() : 90;
        
        // 计算保留天数前的时间
        Date retentionDate = new Date(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(retentionDays));
        log.info("清理截止时间: {} (保留{}天)", retentionDate, retentionDays);

        // 查询需要清理的数据总数
        Long totalCount = bridgeInfoHistoryMapper.countByCreateTimeBefore(retentionDate);
        log.info("需要清理的数据总数: {}", totalCount);

        if (totalCount == 0) {
            log.info("没有需要清理的数据");
            return DataCleanResult.success("bridge_info_history", 0, 0, 0, startTime, new Date());
        }

        // 获取批次大小
        int batchSize = scheduleConfig.getBatchSize() != null ? scheduleConfig.getBatchSize() : 1000;
        log.info("批次大小: {}", batchSize);

        // 分批处理
        int deletedCount = 0;
        int batchNum = 1;
        try {
            while (true) {
                // 小事务批量删除数据
                int batchDeletedCount = deleteBatchByCreateTimeBefore(retentionDate, batchSize);
                
                // 如果本次没有删除任何数据，说明已清理完成
                if (batchDeletedCount == 0) {
                    break;
                }
                
                deletedCount += batchDeletedCount;

                log.info("批次[{}]清理完成，本次清理: {}条，累计清理: {}条，预估剩余: {}条", 
                        batchNum, batchDeletedCount, deletedCount, totalCount - deletedCount);

                batchNum++;
                
                // 为避免短时间内大量操作数据库，添加短暂延迟
                Thread.sleep(100);
            }
        } catch (Exception e) {
            log.error("清理数据过程中发生异常", e);
            return DataCleanResult.failure("bridge_info_history", e.getMessage(), startTime);
        }

        Date endTime = new Date();
        log.info("数据清理任务完成，总共清理: {}条数据，耗时: {}毫秒", deletedCount, endTime.getTime() - startTime.getTime());
        
        return DataCleanResult.success("bridge_info_history", deletedCount, totalCount, batchNum - 1, startTime, endTime);
    }

    /**
     * 小事务批量删除数据
     * @param createTime 截止时间
     * @param limit 限制数量
     * @return 删除的记录数
     */
    @Transactional(rollbackFor = Exception.class)
    public int deleteBatchByCreateTimeBefore(Date createTime, Integer limit) {
        try {
            return bridgeInfoHistoryMapper.deleteBatchByCreateTimeBefore(createTime, limit);
        } catch (Exception e) {
            log.error("批量删除数据失败，截止时间: {}, 限制数量: {}", createTime, limit, e);
            throw e;
        }
    }

}
